package com.vmladenov.cook.ui;

import java.util.ArrayList;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;

import com.vmladenov.cook.R;
import com.vmladenov.cook.core.OnPagedAdapterListener;
import com.vmladenov.cook.core.adapters.ContinuesSmallPreviewListAdapter;
import com.vmladenov.cook.core.html.SmallPreview;
import com.vmladenov.cook.core.loaders.ISmallPreviewLoader;

public abstract class PagedListActivity<TLoader extends ISmallPreviewLoader> extends ListActivity
		implements OnPagedAdapterListener
{
	ProgressDialog progressDialog = null;
	ContinuesSmallPreviewListAdapter<TLoader> adapter;
	View footerView;
	protected TLoader _loader;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.alphabet_recipes);
		progressDialog = null;
		footerView = ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
				.inflate(R.layout.loading_more_footer, null, false);
		this.getListView().addFooterView(footerView);
		_loader = CreateLoader();
		loadFirstData();
	}

	@Override
	protected void onDestroy()
	{
		if (adapter != null) adapter.interuptConsumers();
		super.onDestroy();
	}

	protected void loadFirstData()
	{
		progressDialog = ProgressDialog.show(this, getString(R.string.loading),
				getString(R.string.loading), false);
		Thread readThread = new Thread(new Runnable() {
			@Override
			public void run()
			{
				final ArrayList<SmallPreview> loadedData = _loader.getNextData();
				runOnUiThread(new Runnable() {
					@Override
					public void run()
					{
						showFirstData(loadedData);
						if (progressDialog != null) progressDialog.dismiss();
					}
				});
			}
		});
		readThread.start();
	}

	protected ContinuesSmallPreviewListAdapter<TLoader> CreateAdaptor(
			ArrayList<SmallPreview> loadedData)

	{
		return new ContinuesSmallPreviewListAdapter<TLoader>(this, _loader, loadedData);
	}

	protected abstract TLoader CreateLoader();

	private void showFirstData(ArrayList<SmallPreview> loadedData)
	{
		adapter = CreateAdaptor(loadedData);
		adapter.setEndOfDataListener(this);
		setListAdapter(adapter);
		if (!adapter.hasMore())
		{
			this.onEndOfData();
		}
	}

	@Override
	public void onEndOfData()
	{
		if (footerView != null)
		{
			this.getListView().removeFooterView(footerView);
			footerView = null;
		}
	}
}
